// generateRouter.js
const chalk = require('chalk')
const path = require('path')
const fs = require('fs')
const resolve = (project, ...file) => path.resolve(project, ...file)
const log = message => console.log(chalk.green(`${message}`))
const successLog = message => console.log(chalk.blue(`${message}`))
const errorLog = error => console.log(chalk.red(`${error}`))
//目标js
const routerJspath = './src/router/index.js'
//扫描的vue文件夹
const viewsPath = './src/views'
//js内容模板
const jstemplate = require('./template_router')
const defaultPath = './src/router'
function createRouter (targetPath = defaultPath) {
  const userProjectDirectory = process.cwd()
  log(`按views内结构自动生成router，注意!执行该命令后原有的router配置将会被覆盖！`)
  log(`请输入首页的控件名，回车后会在 ${resolve(userProjectDirectory, targetPath)}目录下生成 index.js`)
  process.stdin.on('data', async chunk => {
    const comstr = String(chunk).trim().toString()
    try {
      if (comstr.length>0) {
        //新增router_autojs,只适用于vue脚手架默认的router位置
        let list= getVueP(viewsPath) ;
        let homePage = '';
        //检验homepage的有效性
        for(let item of list){
          if(item.name==comstr){
            homePage = item.name
            break
          }
        }
        if(homePage.length==0){
            errorLog('homepage not exsiste')
            process.stdin.emit('end')
        }
        // successLog('vue清单：'+JSON.stringify(list))
        let jscontent = jstemplate.jsTemplate(list,homePage)
        await generateFileJS(routerJspath,jscontent)
        successLog('生成index.js')
      } else {
        errorLog('取消操作')
      }
    } catch (e) {
      errorLog(e.message)
    }
    process.stdin.emit('end')
  })
  process.stdin.on('end', () => {
    log('exit')
    process.exit()
  })
}

// 获取指定路径下的所有vue文件作为页面控件
const getVueP = (path)=>{
  let c_list = []
  var pa = fs.readdirSync(path);
	pa.forEach(function(ele,index){
		var info = fs.statSync(path+"/"+ele)	
		if(info.isDirectory()){
			// console.log("dir: "+ele)
			c_list = c_list.concat(getVueP(path+"/"+ele)) ;
		}else{
      if(ele.endsWith('.vue')){
        let idx = ele.indexOf('.vue')
        let compName = ele.substr(0,idx)
        let impPath = path.replace('./src/','@/')
        // let vpath = impPath.substr(7)+'/'+compName
        c_list.push({impPath:impPath+"/"+compName,name:compName,r_path:"/"+compName})
      }
			// console.log("file: "+ele)
    }	
  })
  return c_list
}
const generateFileJS = (path, data) => {
  return new Promise((resolve, reject) => {
    fs.writeFile(path, data, 'utf8', err => {
      if (err) {
        errorLog(err.message)
        reject(err)
      } else {
        resolve(true)
      }
    })
  })
}
module.exports = { createRouter }
